//
//  BBDetail.swift
//  BBetter
//
//  Created by Gmc on 2020/3/10.
//  Copyright © 2020 Gmc. All rights reserved.
//

import UIKit

enum Type {
    case lesson
    case book
    case yo
}

class BBDetail: BBBaseViewController {
    open var id = ""
    private var address:String = ""
//    private var tableView = UITableView()
    private var model:BBDetailModel?
    
    convenience init(type: Type) {
        self.init(nibName: nil, bundle: nil)
        switch type {
        case .lesson:
            do {
                address = "Lesson"
            }
        case .book:
            do {
                address = "Book"
            }
        case .yo:
            do {
                address = "Yo"
            }
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        listenNotification()
        loadData()
        initNavButton()
        initTable()
    }
    
    private func initNavButton() {
        self.navigationItem.rightBarButtonItem = nil
    }
    
    
    private func initTable() {
        view.addSubview(tableView)
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        tableView.register(BBDetailDrawCell.self, forCellReuseIdentifier: "detailDrawCellID")
        tableView.register(BBDetailInfoCell.self, forCellReuseIdentifier: "detailInfoCellID")
        tableView.register(BBDetailCell.self, forCellReuseIdentifier: "detailCellID")
        tableView.snp.makeConstraints { (make) in
            make.leading.trailing.equalTo(view)
            make.top.equalTo(view).offset(0)
            make.bottom.equalTo(view).offset(0)
        }
    }
    private func loadData() {
        Net.loadData(type: .post, para: ["id": id], url: "\(address)/Detail") { (dict: [String: Any]) in
            let success:Bool = dict["success"] as! Bool
            if(success == false) {
                let msgInfo = dict["msgInfo"] as! String
                print(msgInfo)
                return
            } else {
                let data = dict["data"] as! [String: Any]
                self.model = BBDetailModel(dictionary: data)
                self.title = self.model?.name
                self.tableView.reloadData()
            }
        }
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}

extension BBDetail {
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (section == 0 || section == 1) ? 1 : model?.desc.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "detailDrawCellID", for: indexPath) as! BBDetailDrawCell
            if let model = self.model {
                cell.model = model
            }
            return cell
        } else if (indexPath.section == 1) {
            let cell = tableView.dequeueReusableCell(withIdentifier: "detailInfoCellID", for: indexPath) as! BBDetailInfoCell
            if let model = self.model {
                cell.model = model
            }
            return cell
        }
        let cell = tableView.dequeueReusableCell(withIdentifier: "detailCellID", for: indexPath) as! BBDetailCell
        let count = self.model!.desc.count
        cell.model = self.model!.desc[count - indexPath.row - 1]
        return cell
        
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 200
        } else if indexPath.section == 1 {
            return 80
        }
        return 80.0
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.section == 2 {
            let window = UIApplication.shared.windows.first!
            let count = self.model!.desc.count
            let model:BBDetailDescModel = self.model!.desc[count - indexPath.row - 1]
            let view:BBDetailShowView = BBDetailShowView()
            view.show(view: window, text: model.text)
            
        }
    }
}

extension BBDetail {
    private func listenNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(reciveNotification), name: NSNotification.Name(rawValue: BBETTER_PUNCHED_NOTIFICATION), object: nil)
    }
    
    @objc private func reciveNotification() {
        let window = UIApplication.shared.windows.first!
        let punchView = BBPunchCardView()
        punchView.show(view: window)
        punchView.callback = ({[weak self] (data: [String: Any]) in
            var para: [String: Any] = data
            var today:Int = data["today"] as! Int
            guard let model = self?.model else { return }
            if today > model.denominator {
                today = model.denominator
            }
            para["id"]  = model.id
            para["today"] = today
            Net.loadData(type: .post, para: para, url: "\(self!.address)/Punched") { (dict: [String: Any]) in
                let success:Bool = dict["success"] as! Bool
                if(success == false) {
                    let msgInfo = dict["msgInfo"] as! String
                    print(msgInfo)
                    return
                } else {
                    let data = dict["data"] as! [String: Any]
                    self?.model = BBDetailModel(dictionary: data)
                    self?.tableView.reloadData()
                    self?.sendMessageToParent(obj: ["id": self?.model?.id])
                }
            }
        })
        
    }
}
